package com.cwx.service;

import com.cwx.NotFoundException;
import com.cwx.dao.BlogRepository;
import com.cwx.pojo.Blog;
import com.cwx.pojo.Type;
import com.cwx.utils.MarkDownUtils;
import com.cwx.vo.BlogQuery;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.*;
import javax.transaction.Transactional;
import java.util.*;

@Service
public class BlogServiceImpl implements BlogService{

    @Autowired
    private BlogRepository blogRepository;

    @Transactional
    @Override
    public Blog getBlog(Long id) {
        return blogRepository.getOne(id);
    }

    @Transactional
    @Override
    //动态查询分页
    public Page<Blog> listBlog(Pageable pageable, BlogQuery blog) {
        return blogRepository.findAll(new Specification<Blog>() {
            @Override  //root 要查询的对象    query  条件的容器   criteriaBuilder  设置条件的表达式
            public Predicate toPredicate(Root<Blog> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<>();
                if ("".equals(blog.getTitle()) && blog.getTitle() != null){
                    predicates.add(cb.like(root.<String>get("title"), "%"+blog.getTitle()+"%"));
                }

                if (blog.getTypeId() != null) {
                    predicates.add(cb.equal(root.<Type>get("type").get("id"), blog.getTypeId()));
                }

                if (blog.isRecommend()){
                    predicates.add(cb.equal(root.<Boolean>get("recommend"),blog.isRecommend()));
                }

                cq.where(predicates.toArray(new Predicate[predicates.size()]));
                return null;
            }
        },pageable);
    }

    //查询所有博客  分页
    @Transactional
    @Override
    public Page<Blog> listBlog(Pageable pageable) {
        return blogRepository.findAll(pageable);
    }

    @Transactional
    @Override
    public Blog saveBlog(Blog blog) {


        if (blog.getId() == 0) {
            //创建博客时  给他设置一些初始值
            blog.setCreateTime(new Date());
            blog.setUpdateTime(new Date());
            blog.setViews(0);   //浏览量默认值是null  所以要先给他设置为0   也可以在实体类的时候就给他设置为0
        }else {
            blog.setCreateTime(createTime(blog.getId()));
            blog.setUpdateTime(new Date());
        }
        return blogRepository.save(blog);
    }

    private Date createTime(Long id) {
        Blog byId = blogRepository.getById(id);
        return byId.getCreateTime();
    }

    @Transactional
    @Override
    public Blog updateBlog(Long id, Blog blog) {
        Blog one = blogRepository.getOne(id);
        if (one == null){
            throw new NotFoundException("你要修改的博客找不到");
        }
        BeanUtils.copyProperties(blog,one);   //前面的赋值给后面的
        return blogRepository.save(one);
    }

    @Transactional
    @Override
    public void deleteBlog(Long id) {
        blogRepository.deleteById(id);
    }

    //按照更新时间查出最新的博客
    @Transactional
    @Override
    public List<Blog> listBlogTop(Integer size) {
        Sort sort = Sort.by(Sort.Direction.DESC,"updateTime");
        Pageable pageable = PageRequest.of(0,size,sort);

        return blogRepository.findTop(pageable);
    }

    //查询博客的业务
    @Transactional
    @Override
    public Page<Blog> ListBlogSearch(String query, Pageable pageable) {
        return blogRepository.findBySearch(query,pageable);
    }

    //根据Id查找制定博客并把他转换为html文本返回
    @Transactional
    @Override
    public Blog getAndConvert(Long id) {
        Blog blog = blogRepository.findById(id).orElse(null);

        if (blog == null){
            throw new NotFoundException("该博客不存在");
        }

        Blog b = new Blog();
        BeanUtils.copyProperties(blog,b); //前面的复制给后面的  由于直接修改查询到blog会导致数据库中的内容也改变 所以在创建一个blog把查到的复制给新建的

        String content = b.getContent();
        b.setContent(MarkDownUtils.markdownToHtml(content));

        //每次点击的时候 浏览次数加一
        blogRepository.updateViews(id);

        return b;
    }

    //根据博客的标签id来查询博客
    //连接博客表和标签表
    @Override
    public Page<Blog> listBlog(Long tagId, Pageable pageable) {
        return blogRepository.findAll(new Specification<Blog>() {
            @Override //root 要查询的对象    query  条件的容器   criteriaBuilder  设置条件的表达式
            public Predicate toPredicate(Root<Blog> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
                Join join = root.join("tags");  //连接标签表 参数是blog类中的标签
                return cb.equal(join.get("id"),tagId );  //如果标签表中的id 和我们传过来的tagId相等就返回
            }
        },pageable);
    }

    @Override
    public Map<String, List<Blog>> archivers() {
        TreeMap<String,List<Blog>> map = new TreeMap<>((o1, o2)->Integer.parseInt(o2)-Integer.parseInt(o1));
        List<String> years = blogRepository.findGroupYear();
        for (String year : years){
            map.put(year,blogRepository.findByYear(year));
        }
        return map;
    }

    @Override
    public Long countBlog() {
        return blogRepository.count();
    }
}
